<template>
  <!-- pages/pay/index.wxml -->

  <view class="recharge">
    <view class="recharge-box">
      <view>
        <view class="tips">
          <image
            class="icon-map-zhan"
            src="/static/images/icon-map-zhuang.png"
          ></image>
          充电桩编号:{{ device_code }}
        </view>
      </view>

      <!-- <view class='price-detail1'>
      <view class="detail-time1">
        <view class="time-duan-box" >当前时段
          <view class="time-duan1">({{kv.startH}}:{{kv.startM}}-{{kv.endH}}:{{kv.endM}})</view>
        </view>
        <view class="time-detail" bind:tap="openPopup">
          <view>详情
            <van-icon name="arrow" size="14" />
          </view>
        </view>
      </view>
      <view class="detail-money">
        <view class="money-total"> 
          <text class="money-total-title">电价</text>
          <view class="money-total-num"><text class="money-total-num-icon">¥</text>{{filters.addPrice(kv.ePrice,kv.sPrice)}}</view>
        </view>
        <view class="money-item">
         <view class="money-item-name"><van-icon name="balance-o" color="#FF6B03" size="20" style="margin-right: 4rpx;"/>电费</view>
         <text class="money-item-num">¥{{filters.Price4Point(kv.ePrice)}}</text>
        </view>
        <view class="money-item">
         <view class="money-item-name"><van-icon name="balance-pay" color="#FF6B03" size="20" style="margin-right: 4rpx;"/>服务费</view>
         <text  class="money-item-num">¥{{filters.Price4Point(kv.sPrice)}}</text>
        </view>
      </view>
    </view> -->

      <view class="price-detail1">
        <view class="detail-money">
          <view class="money-total">
            <view class="detail-time1">
              <view class="time-duan-box">
                当前时段
                <view class="time-duan1"
                  >( {{ kv.startH }}:{{ kv.startM }}-{{ kv.endH }}:{{
                    kv.endM
                  }}
                  )</view
                >
              </view>
              <view class="time-detail" @click="openPopup">
                <view>
                  查看详情
                  <!-- <van-icon name="arrow" size="14" /> -->
                </view>
              </view>
            </view>

            <view class="money-item">
              <view class="money-item-name money-item-name-total"
                >当前单价</view
              >
              <text class="money-item-num">
                ¥ {{ addPrice(kv.ePrice, kv.sPrice) }}
                <text class="money-item-num-du">元/度</text>
              </text>
            </view>

            <view class="money-item">
              <view class="money-item-name">
                <image class="u-icon" src="/static/icon/balance-o.png"></image>
                电费
              </view>
              <text class="money-item-num">
                ¥ {{ Price4Point(kv.ePrice) }}
                <text class="money-item-num-du">元/度</text>
              </text>
            </view>

            <view class="money-item">
              <view class="money-item-name">
                <image
                  class="u-icon"
                  src="/static/icon/balance-pay.png"
                ></image>
                服务费
              </view>
              <text class="money-item-num">
                ¥ {{ Price4Point(kv.sPrice) }}
                <text class="money-item-num-du">元/度</text>
              </text>
            </view>
          </view>
        </view>
      </view>

      <view class="title">输入或者选择要充电的预付金额：</view>
      <view class="input-box">
        <input
          class="input"
          type="number"
          placeholder="请输入整数金额(单位元)"
          v-model="money"
        />
      </view>

      <view class="item-num">
        <view
          :class="money == 10 ? 'num1 checked' : 'num1'"
          data-amount="10"
          @tap="choose"
          >10元</view
        >
        <view
          :class="money == 20 ? 'num checked' : 'num default'"
          data-amount="20"
          @tap="choose"
          >20元</view
        >
        <view
          :class="money == 30 ? 'num checked' : 'num default'"
          data-amount="30"
          @tap="choose"
          >30元</view
        >
      </view>

      <view class="item-num">
        <view
          :class="money == 50 ? ' num1 checked' : 'num1 default'"
          data-amount="50"
          @tap="choose"
          >50元</view
        >
        <view
          :class="money == 100 ? ' num checked' : 'num default'"
          data-amount="100"
          @tap="choose"
          >100元</view
        >
        <view
          :class="money == 200 ? ' num checked' : 'num default'"
          data-amount="200"
          @tap="choose"
          >200元</view
        >
      </view>

      <view class="btn btn-primary btn-recharge" @tap="clickRecharge"
        >充电</view
      >
      <!-- <view class='title'>您的当前余额 {{balance}}元</view> -->

      <!-- 新增电价详情弹出 -->
      <uni-popup ref="popup" type="right" style="width: 100%">
        <view class="pop-box">
          <view class="title-bar">
            <uni-icons type="left" size="30" @click="closePopup"></uni-icons>
            <text class="time-duan">{{ "时段" }}</text>
            <view class="title-name">
              <view class="view-name">
                <text>电价</text>
                <text>{{ "(元/度)" }}</text>
              </view>
              <view class="name-icon">=</view>
              <view class="view-name">
                <text>电费</text>
                <text>{{ "(元/度)" }}</text>
              </view>
              <view class="name-icon">+</view>
              <view class="view-name">
                <text>服务费</text>
                <text>{{ "(元/度)" }}</text>
              </view>
            </view>
          </view>
          <view class="pop-time-info">
            <view :class="'time-box ' + ''">
              <block v-for="(item, index) in kvAll" :key="index">
                <view
                  :class="
                    'time-card ' +
                    (getNowTime() >= item.startH && getNowTime() < item.endH
                      ? 'time-card-active'
                      : '') +
                    ' '
                  "
                >
                  <view
                    class="now-tag"
                    v-if="
                      getNowTime() >= item.startH && getNowTime() < item.endH
                    "
                    >当前时段</view
                  >
                  <view class="card-left">
                    <uni-tag
                      :inverted="true"
                      :text="item.timeType"
                      type="primary"
                      size="small"
                      v-if="item.timeType == '平'"
                    />
                    <uni-tag
                      :inverted="true"
                      :text="item.timeType"
                      type="primary"
                      size="small"
                      v-if="item.timeType == '峰'"
                    />
                    <uni-tag
                      :inverted="true"
                      :text="item.timeType"
                      type="success"
                      size="small"
                      v-if="item.timeType == '谷'"
                    />
                    <view class="text"
                      >{{ item.startH }}:{{ item.endH }} - {{ item.endH }}:{{
                        item.endM
                      }}</view
                    >
                  </view>

                  <view class="card-right">
                    <view class="price">{{
                      addPrice4Point(item.ePrice, item.sPrice)
                    }}</view>
                    <view class="eprice">{{ Price4Point(item.ePrice) }}</view>
                    <view class="sprice">{{ Price4Point(item.sPrice) }}</view>
                  </view>
                </view>
              </block>
            </view>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>
<!-- <script module="filters" lang="wxs" src="@/pages/utils/filter.wxs"></script> -->
<script>
import { Price4Point, addPrice4Point, getNowTime, addPrice } from "@/utils/util"
const app = getApp();
let Store = app.globalData.Store;
let Sign = app.globalData.Sign;
let Api = app.globalData.Api;
export default {
  components: {
  },
  //1 参数 device_code
  data() {
    return {
      Price4Point: Price4Point,
      addPrice4Point: addPrice4Point,
      getNowTime: getNowTime,
      addPrice: addPrice,
      gobugo: true,
      user_id: '',
      balance: 0,
      money: '',
      device_code: '',
      show: false,

      kv: {
        startH: '',
        startM: '',
        endH: '',
        endM: ''
      },

      kvAll: ''
    };
  },
  onLoad: function (options) {
    //根据业务场景，获取设备信息以及定价策略
    this.judgeToData(options.device_code);
  },
  onShow: function () {
    // this.setData({
    this.user_id = Store.getItem('user_id')
    // });
  },
  methods: {
    //初始检查
    judgeToData: function (code) {
      //1 拼接终端 存储数据
      let code_pin = null;
      if (code.indexOf('_') > 0) {
        var codeAr = code.split('_');
        var preCode = codeAr[0];
        var sub = parseInt(codeAr[1]);
        code_pin = preCode + (sub < 10 ? '_0' + sub : '_' + sub);
      } else {
        code_pin = code;
      }
      // this.setData({
      this.balance = Store.getItem('balance'),
        this.device_code = code_pin
      // });
      Store.setItem('device_code', code_pin);

      //2 展示定价策略
      this.getPriceCelue(code_pin);

      //3 判断用户是否登录
      let that = this;
      let user_id = Store.getItem('user_id');
      if (user_id) {
        // that.setData({
        that.user_id = user_id
        // });
      } else {
        if (that.gobugo) {
          //更新跳转标识
          // that.setData({
          that.gobugo = false
          // });
          //前往获取 userId
          setTimeout(function () {
            uni.redirectTo({
              url: '../sysLogin/sysLogin?pay_source=FROM_TID_NEW'
            });
          }, 1000);
        }
      }
    },

    // checkMachine: function (device_pin) {
    //   let this_ = this
    //   let thisStat = -100;
    //   if (device_pin) {
    //     const signObject = {
    //       device_pin
    //     };
    //     const signvalue = Sign.signutil(signObject)
    //     app.get(Api.getMachineInfo, {
    //       device_pin,
    //       sign: signvalue
    //     }).then((res) => {
    //       if (res.code == -1) {
    //         this_.toast.showToast("充电桩", 2000)
    //       } else {
    //         thisStat = res.machine.stat
    //       }
    //     }).catch((e) => {
    //       console.log(e)
    //     })
    //   }
    //   this.setData({
    //     devStatus: thisStat
    //   })
    // },

    getPriceCelue(device_code) {
      let this_ = this;
      const signObject = {
        device_code
      };
      const signvalue = Sign.signutil(signObject);
      app.globalData
        .get(Api.geNewTcpPrice, {
          device_code,
          sign: signvalue
        })
        .then((res) => {
          this.kv = res.kv[0],
            this.kvAll = res.kvAll
          // 模拟数据
          // this.kv = { startH: '19:00:00', endH: '20:00:00', timeType: '平', endM: '21:00:00', ePrice: '10', sPrice: '20' },
          // this.kvAll = [{ startH: '17', endH: '20', timeType: '平', endM: '21', ePrice: '10', sPrice: '20' },
          // { startH: '19:00:00', endH: '20:00:00', timeType: '平', endM: '21:00:00', ePrice: '10', sPrice: '20' },
          // { startH: '19:00:00', endH: '20:00:00', timeType: '平', endM: '21:00:00', ePrice: '10', sPrice: '20' },
          // { startH: '19:00:00', endH: '20:00:00', timeType: '平', endM: '21:00:00', ePrice: '10', sPrice: '20' },
          // { startH: '19:00:00', endH: '20:00:00', timeType: '平', endM: '21:00:00', ePrice: '10', sPrice: '20' },
          // { startH: '19:00:00', endH: '20:00:00', timeType: '平', endM: '21:00:00', ePrice: '10', sPrice: '20' }]
          // });
        })
        .catch((e) => {
          console.log(e);
        });
    },

    //手动输入金额
    getMoney(e) {
    console.log('e: ', e);
      let amount = e.detail.value;
      // this.setData({
      this.money = amount
      // });
    },

    //点选按钮
    choose(e) {
      let data = e.currentTarget.dataset;
      // this.setData({
      this.money = data.amount
      // });
      //console.log(this.data.money);
    },

    /**
     * 充电流程 1 用户扫码进入选择金额的界面
     *    1.1 提示预付款的金额
     *    1.2 跳转时 下发自检
     *    1.3 数据库查询最新的充电桩状态 一一进行判断
     */
    clickRecharge() {
      let this_ = this;
      //1 获取最新的充电桩状态
      let device_code = this.device_code;
      if (device_code) {
        const signObject = {
          device_code
        };
        const signvalue = Sign.signutil(signObject);
        app.globalData
          .get(Api.getMachineInfo, {
            device_code,
            sign: signvalue
          })
          .then((res) => {
            let devStatus = res.machine.stat;
            console.log('充电桩状态' + devStatus);
            if (devStatus == '1') {
              //判断金额
              if (this_.checkMoney(this_.money)) {
                const uuu = '../tidNEWToPay/tidNEWToPay?user_id=' + this_.user_id + '&device_code=' + this_.device_code + '&price=' + this_.money;
                console.log(uuu);
                uni.navigateTo({
                  url: uuu
                });
              } else {
                uni.showToast({
                  title: '请选择金额或输入整数金额!',
                  icon: 'none',
                  duration: 1500
                });
              }
            } else {
              uni.showModal({
                title: '',
                content: '充电桩' + this_.changeMachineTrueStatus(devStatus),
                success(res) {
                  if (res.confirm) {
                  } else if (res.cancel) {
                  }
                }
              });
            }
          })
          .catch((e) => {
            if (e.code == -1) {
              setTimeout(() => {
                uni.showToast({
                  title: '未查询到该充电桩!',
                  icon: 'none',
                  duration: 1500
                });
                setTimeout(() => {
                  uni.hideToast();
                }, 2000);
              }, 500);
            }
          });
      }
    },

    changeMachineTrueStatus(stat) {
      if (stat == '0') {
        return '请插枪';
      }
      if (stat == '1') {
        return '连接中';
      }
      if (stat == '2') {
        return '充电中';
      }
      if (stat == '4') {
        return '故障';
      }
      if (stat == '-1') {
        return '离线';
      }
      return '状态异常';
    },

    checkMoney: function (money) {
      if (money != '' && money != null) {
        var moneyString = money.toString();
        if (moneyString.indexOf('.') == -1 && moneyString.indexOf('。') == -1) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },

    // 关闭电价详情弹窗
    closePopup() {
      this.$refs.popup.close()
      // this.setData({
      // this.show = false
      // });
    },

    openPopup() {
      this.$refs.popup.open()
      // this.setData({
      // this.show = true
      // });
    },

    onClose() {
      console.log('占位：函数 onClose 未声明');
    }
  }
};
</script>
<style>
@import "./tidNEWSelMoney.css";
</style>
